package cn.dakaqi.validator;

import cn.dakaqi.annotation.SqlInjection;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


public class SqlInjectionValidator implements ConstraintValidator<SqlInjection, String> {

    public void initialize(SqlInjection constraintAnnotation) {
    }

    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        if (null != object) {
            return this.sqlValidate(object);
        }
        return true;
    }

    protected boolean sqlValidate(String str) {
        str = str.toLowerCase();
        String badStr = "'exec |execute |insert |select |delete |update |count |drop |chr |mid |master |truncate |"
                + "char |declare |sitename |net user |xp_cmdshell |like'|create |"
                + "table |from |grant |use |group_concat |column_name |"
                + "information_schema.columns|table_schema|union |where |order |by |like ";
        // String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|"
        // + "char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|"
        // + "table|from|grant|use|group_concat|column_name|"
        // + "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|"
        // + "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#";// 过滤掉的sql关键字，可以手动添加
        String[] badStrs = badStr.split("\\|");
        for (int i = 0; i < badStrs.length; i++) {
            if (str.indexOf(badStrs[i]) >= 0) {
                System.err.println("SQL injection verification is not passed：" + str);
                return false;
            }
        }
        return true;
    }
}